package com.lagou.web;

import com.lagou.domain.User;
import com.lagou.service.CheckLogin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Administrator
 */

public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取表单信息 用户名和密码
        String username = req.getParameter("username");
        System.out.println("username : " +username);

        String password = req.getParameter("password");
        System.out.println("password :" + password);

        if(username == null || password == null || username.isBlank() || password.isBlank()){
            System.out.println("请输入用户名和密码!");
            //响应给页面
            resp.getWriter().write("请输入用户名和密码!");
        }else{
            //去掉空格
            String userName = username.trim();
            String passWord = password.trim();
            User user = new User(userName, passWord);

            //2.判断用户名是否存在
            CheckLogin checkLogin = new CheckLogin(user);
            boolean flag = checkLogin.login();
            if(flag){
                System.out.println("登录成功");
                //获取session
                HttpSession session=req.getSession();
                //把用户名添加到session中
                session.setAttribute("username",userName);
                resp.getWriter().write("登录成功");
            }else{
                System.out.println("登录失败，密码错误");
                resp.getWriter().write("登录失败，密码错误");
            }
        }

    }
}
